package com.itheima.reggie.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.swing.ScreenUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.comon.CustomException;
import com.itheima.reggie.comon.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Transactional
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    //登录
    @Override
    public ResultInfo<Employee> login(Employee employee) {
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emLogin = employeeMapper.selectOne(wrapper);
        //判断用户名是否存在
        if (emLogin == null) {
            return ResultInfo.error("用户名不存在");
        }
        //将传入的密码加密
        String password = employee.getPassword();
        String passwordMd5 = SecureUtil.md5(password);

        //判断密码是否一致
        if (!StringUtils.equals(emLogin.getPassword(), passwordMd5)) {
            return ResultInfo.error("用户名或密码错误");
        }
        //判断用户账户状态是否启用
        if (Objects.equals(emLogin.getStatus(), Employee.STATUS_DISABLE)) {
            return ResultInfo.error("账户已被禁用,请联系您的管理员");
        }
        return ResultInfo.success(emLogin);
    }


    //查询
    @Override
    public List<Employee> findAllAndByName(String name) {
        return employeeMapper.findAllAndByName(name);
    }

    //添加
    @Override
    public void insert(Employee employee) {
        if (Objects.equals(employee.getName(), "") && Objects.equals(employee.getUsername(), "")) {
            throw new CustomException("名字和账号不能为空");
        }
     /*   //添加id
        employee.setId(IdUtil.createSnowflake(1, 1).nextId());*/
      /*  //密码设置默认
        employee.setPassword(SecureUtil.md5("123456"));
        //权限设置为开
        employee.setStatus(Employee.STATUS_ENABLE);*/
/*        //插入时间和更新时间
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());
        //插入人和修改人
        employee.setCreateUser(1L);
        employee.setUpdateUser(1L);*/
        employeeMapper.insert(employee);
    }

    //修改和查询
    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);

    }

}
